package com.lsx143.wordcount.day5;

import com.lsx143.wordcount.bean.WaterSensor;
import com.lsx143.wordcount.util.MyUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

import java.util.List;

public class Flink_TumblingWindowFunction_Process {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env
                .socketTextStream("hadoop162", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String line, Collector<WaterSensor> out) throws Exception {
                        String[] datas = line.split(",");
                        out.collect(new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2])));
                    }
                })
                .keyBy(WaterSensor::getId)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(
                        new ProcessWindowFunction<WaterSensor, Double, String, TimeWindow>() {
                            @Override
                            public void process(String key,
                                                Context ctx,
                                                Iterable<WaterSensor> elements,
                                                Collector<Double> out) throws Exception {
                                List<WaterSensor> waterSensors = MyUtil.toList(elements);
                                System.out.println("Flink_TumblingWindowFunction_Process.process");
                                System.out.println("size = " + waterSensors.size());
                            }
                        }
                )
                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}